package cn.szabadsag.hrm.service.impl;

import cn.szabadsag.hrm.client.AuthServiceClient;
import cn.szabadsag.hrm.domain.Employee;
import cn.szabadsag.hrm.domain.LoginUser;
import cn.szabadsag.hrm.domain.Tenant;
import cn.szabadsag.hrm.dto.LoginUserDto;
import cn.szabadsag.hrm.dto.TenantEnteringDto;
import cn.szabadsag.hrm.exception.Assert;
import cn.szabadsag.hrm.exception.ErrorCode;
import cn.szabadsag.hrm.mapper.EmployeeMapper;
import cn.szabadsag.hrm.mapper.TenantMapper;
import cn.szabadsag.hrm.query.TenantQuery;
import cn.szabadsag.hrm.service.ITenantService;
import cn.szabadsag.hrm.util.AjaxResult;
import cn.szabadsag.hrm.util.PageList;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangcong
 * @since 2022-04-04
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private AuthServiceClient authServiceClient;


    @Override
    public PageList<Tenant> selectPageList(Page<Tenant> page, TenantQuery query) {
        //  查询当前页数据
        List<Tenant> datas = tenantMapper.loadPageList(page,query);
        //  返回满足条件的数据
        return new PageList<>(page.getTotal(),datas);
    }

    @Override
    public void entering(TenantEnteringDto enteringDto) {
        //1 参数校验
        //1.1 非空检验
        /**
         * 不需要在这里做非空检验，因为已经在TenantEnteringDto的字段上做了非空处理
         */
//        if (enteringDto == null)
//            throw new RuntimeException("参数错误！");
        //Assert.assertNotNull(enteringDto,"参数错误！");
        //Assert.assertNotNull(enteringDto.getEmployee(),"参数错误！");
        //Assert.assertNotNull(enteringDto.getMealId(),"参数错误！");
        //Assert.assertNotNull(enteringDto.getTenant(),"参数错误！");
        //1.2 机构唯一性校验
        List<Tenant>  tenants = tenantMapper.selectList(new EntityWrapper<Tenant>()
                .eq("company_name",enteringDto.getTenant().getCompanyName()));
        /*if (tenants != null && tenants.size() > 0)
            throw new RuntimeException("该机构已入驻！请直接登录！！");*/
        Assert.assertListNull(tenants, ErrorCode.CODE_400_TENANT_EXSIT);
        //1.3 管理员校验
        //方案1：如果已经存在，不需要添加管理员，但是要校验身份，如果校验通过，直接添加租户信息，不需要添加管理员信息，还要维护套餐信息。---比较麻烦
        //方案2：如果管理员已经存在，让他登录进去直接添加 ---采纳
        List<Employee> employees = employeeMapper.selectList(new EntityWrapper<Employee>()
                .eq("username",enteringDto.getEmployee().getUsername()));
        /*if (employees != null && employees.size() > 0)
            throw new RuntimeException("该管理员已经有机构！请登录后添加新的机构！");*/
        Assert.assertListNull(employees, ErrorCode.CODE_400_TENANT_ADMIN_EXSIT);

        //2 远程调用auth feign接口添加loginUser维护套餐信息后返回loginId
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(enteringDto.getEmployee().getUsername());
        loginUser.setPassword(enteringDto.getEmployee().getPassword());
        loginUser.setType(0);

        LoginUserDto loginUserDto = new LoginUserDto();
        loginUserDto.setLoginUser(loginUser);
        loginUserDto.setMealId(enteringDto.getMealId());

        AjaxResult ajaxResult = authServiceClient.add(loginUserDto);
        /*if (!ajaxResult.isSuccess())
            throw new RuntimeException("系统错误！！");*/
        Assert.assertTrue(ajaxResult.isSuccess(),ErrorCode.CODE_500_SYSTEM_ERROR.getMeesage());

        Long loginId = Long.valueOf(ajaxResult.getResultObj().toString());

        //3 添加管理员信息并返回adminId
        Employee employee = enteringDto.getEmployee();
        employee.setLoginId(loginId);
        employeeMapper.insert(employee);

        //4 添加租户信息
        Long adminId = employee.getId();
        Tenant tenant = enteringDto.getTenant();
        tenant.setAdminId(adminId);
        tenantMapper.insert(tenant);

    }
}
